<template>
  <el-dialog
      title="添加信息"
      v-model="dialogVisibleAdd"
      width="800px"
      @close="resetFormData"
  >
    <el-form ref="addDataForm" :model="addData" label-width="120px">
      <!-- 以下是直接写入的各个表单字段 -->
      <el-form-item
          label="学期"
          prop="term"
          :rules="allrules.term"
      >
        <el-input v-model="addData.term" placeholder="请输入学期"/>
      </el-form-item>
      <el-form-item
          label="类型"
          prop="type"
          :rules="allrules.type"
      >
        <el-select
            v-model="addData.type"
            placeholder="请选择类型">
          <!--          调课('调课', '调课'), ('停课', '停课'), ('补课', '补课'), ('代课', '代课'), ('拆/合班', '拆/合班'), 不要使用v-for-->
          <el-option
              label="调课"
              value="调课"
          />
          <el-option
              label="停课"
              value="停课"
          />
          <el-option
              label="补课"
              value="补课"
          />
          <el-option
              label="代课"
              value="代课"
          />
          <el-option
              label="拆合班"
              value="拆合班"
          />
        </el-select>
      </el-form-item>
      <el-form-item
          label="变更类型"
          prop="change_type"
          :rules="allrules.change_type"
      >
        <el-select v-model="addData.change_type" placeholder="请选择变更类型">
          <!--          变更类"临时", "临时"), ("长期", "长期"), 不要使用v-for-->
          <el-option
              label="临时"
              value="临时"
          />
          <el-option
              label="长期"
              value="长期"
          />

        </el-select>
      </el-form-item>

      <el-form-item
          label="课程名称"
          prop="course_name"
          :rules="allrules.course_name"
      >
        <el-input v-model="addData.course_name" placeholder="请输入课程名称"/>
      </el-form-item>

      <el-form-item
          label="原班级"
          prop="original_class"
          :rules="allrules.original_class"
      >
        <el-input v-model="addData.original_class" placeholder="请输入原班级"/>
      </el-form-item>

      <el-form-item
          label="原周次"
          prop="original_week"
          :rules="allrules.original_week"
      >
        <el-input v-model="addData.original_week" placeholder="请输入原周次(例:1 或 1-9)"/>
      </el-form-item>
      <el-form-item
          label="原节次"
          prop="original_class_time"
          :rules="allrules.original_class_time"
      >
        <el-input v-model="addData.original_class_time" placeholder="请输入原节次（例：一/1-3）"/>
      </el-form-item>
      <el-form-item
          label="原教室"
          prop="original_room"
          :rules="allrules.original_room"
      >
        <!--        新教室按下拉选择，选择内容为config.our_classroom中的内容（是一个list）-->
        <el-select

            v-model="addData.original_room"
            filterable
            allow-create
            placeholder="请选择教室"
        >
          <el-option
              v-for="item in our_classroom"
              :key="item"
              :label="item"
              :value="item"
          />
        </el-select>
      </el-form-item>

      <el-form-item
          label="新周次"
          prop="new_week"
          :rules="allrules.new_week"
      >
        <el-input v-model="addData.new_week" placeholder="请输入新周次"/>
      </el-form-item>
      <el-form-item
          label="新节次"
          prop="new_class_time"
          :rules="allrules.new_class_time"
      >
        <el-input v-model="addData.new_class_time" placeholder="请输入新节次（例：二/1-3）"/>
      </el-form-item>
      <el-form-item
          label="新教室"
          prop="new_room"
          :rules="allrules.new_room"
      >
        <!--        新教室按下拉选择，选择内容为config.our_classroom中的内容（是一个list）-->
        <el-select
            v-model="addData.new_room"
            filterable
            allow-create
            placeholder="请选择教室"
        >
          <el-option
              v-for="item in our_classroom"
              :key="item"
              :label="item"
              :value="item"
          />
        </el-select>
      </el-form-item>

      <el-form-item
          label="原因类型"
          prop="reason_type"
          :rules="allrules.reason_type"
      >
        <el-select v-model="addData.reason_type" placeholder="请选择原因类型">
          <!--          因公 因私 不要使用v-for-->
          <el-option
              label="因公"
              value="因公"
          />
          <el-option
              label="因私"
              value="因私"
          />
        </el-select>
      </el-form-item>
      <el-form-item
          label="原因"
          prop="reason"
          :rules="allrules.reason"
      >
        <el-input v-model="addData.reason" type="textarea" placeholder="请输入原因"/>
      </el-form-item>

      <!-- 其他字段按相同方式添加 -->
      <!-- ... -->

      <el-form-item>
        <el-button
            type="primary"
            :loading="SubmitAddLoading"
            :disabled="SubmitAddLoading"
            @click="handleSubmitAdd"
        >
          {{ SubmitAddLoading ? '正在添加' : '确认' }}
        </el-button>
        <el-button @click="dialogVisibleAdd = false">取 消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>

  <AddAuthor ref="addAuthorComponent" :Type="'add'"/>
</template>
<script setup>
import {onMounted, reactive, ref} from 'vue';
import {ElMessage} from "element-plus";
import AddAuthor from "@/components/Main/ReportManagement/AddAuthor.vue";
import {jsonApi} from "@/global.js";

// 设置接受的变量
const props = defineProps({
  isAdmin: {
    type: Boolean,
    required: true
  }
});

const allrules = {
  term: [
    {required: true, message: '字段不能为空', trigger: 'blur'},
    // 其他规则...
  ],
  type: [
    {required: true, message: '字段不能为空', trigger: ['change', 'blur'] },
  ],
  change_type: [
    {required: true, message: '字段不能为空', trigger: ['change', 'blur'] },
  ],
  course_name: [
    {required: true, message: '字段不能为空', trigger: 'blur'},
    // 其他规则...
  ],
  original_class: [
    {required: true, message: '字段不能为空', trigger: 'blur'},
    // 其他规则...
  ],
  original_week: [
    {required: true, message: '字段不能为空', trigger: 'blur'},
    {
      validator: (rule, value, callback) => {
        // 检查是否为单个数字或区间
        if (/^([1-9]|1[0-9])$/.test(value)) { // 单个数字，1到19
          return callback();
        } else if (/^(([1-9]|1[0-9])-([1-9]|1[0-9]))$/.test(value)) { // 数字区间，如1-2, 3-4等
          const [start, end] = value.split('-').map(num => parseInt(num, 10));
          // 确保起始数字小于结束数字且都在1-19范围内
          if (start < end && start >= 1 && end <= 19) {
            return callback();
          }
        }
        return callback(new Error('请输入1-19之间的数字或者类似1-2这样的区间（区间也必须在1-19内），如仅停课则不填写'));
      },
      trigger: 'blur'
    },
  ],
  original_class_time: [
    {required: true, message: '字段不能为空', trigger: 'blur'},
    {
      validator: (rule, value, callback) => {
        // 正则匹配：星期（一到日）和节次（1-13的单个或范围）
        const regex = /^([一二三四五六日])\/(\d{1,2}(?:-\d{1,2})?)$/;
        const match = value.match(regex);

        if (match) {
          const sessionPart = match[2];
          const sessions = sessionPart.split('-');

          if (sessions.length === 1) {
            const session = parseInt(sessions[0], 10);
            if (session >= 1 && session <= 13) {
              return callback();
            }
          } else if (sessions.length === 2) {
            const start = parseInt(sessions[0], 10);
            const end = parseInt(sessions[1], 10);
            if (
                start >= 1 &&
                end <= 13 &&
                start < end
            ) {
              return callback();
            }
          }
        }

        // 格式错误或节次范围非法
        return callback(new Error('格式错误，请按照 星期/节次 格式，例：二/1-3'));
      },
      trigger: 'blur'
    }
    // 其他规则...
  ],
  original_room: [
    {required: true, message: '字段不能为空', trigger: ['change', 'blur'] },
    // 其他规则...
  ],
  new_room: [
  ],
  new_week: [
    {
      validator: (rule, value, callback) => {
        if (!value) {
          return callback(); // 但实际应由 required 规则处理，此处可删除
        }
        // 检查是否为单个数字或区间
        if (/^([1-9]|1[0-9])$/.test(value)) { // 单个数字，1到19
          return callback();
        } else if (/^(([1-9]|1[0-9])-([1-9]|1[0-9]))$/.test(value)) { // 数字区间，如1-2, 3-4等
          const [start, end] = value.split('-').map(num => parseInt(num, 10));
          // 确保起始数字小于结束数字且都在1-19范围内
          if (start < end && start >= 1 && end <= 19) {
            return callback();
          }
        }
        return callback(new Error('请输入1-19之间的数字或者类似1-2这样的区间（区间也必须在1-19内），如仅停课则不填写'));
      },
      trigger: 'blur'
    },
  ],
  new_class_time: [
    {
      validator: (rule, value, callback) => {
        if (!value) {
          return callback(); // 但实际应由 required 规则处理，此处可删除
        }
        // 正则匹配：星期（一到日）和节次（1-13的单个或范围）
        const regex = /^([一二三四五六日])\/(\d{1,2}(?:-\d{1,2})?)$/;
        const match = value.match(regex);

        if (match) {
          const sessionPart = match[2];
          const sessions = sessionPart.split('-');

          if (sessions.length === 1) {
            const session = parseInt(sessions[0], 10);
            if (session >= 1 && session <= 13) {
              return callback();
            }
          } else if (sessions.length === 2) {
            const start = parseInt(sessions[0], 10);
            const end = parseInt(sessions[1], 10);
            if (
                start >= 1 &&
                end <= 13 &&
                start < end
            ) {
              return callback();
            }
          }
        }

        // 格式错误或节次范围非法
        return callback(new Error('格式错误，请按照 星期/节次 格式，例：二/1-3'));
      },
      trigger: 'blur'
    }
    // 其他规则...
  ],
  reason_type: [
    {required: true, message: '字段不能为空', trigger: ['change', 'blur'] },
  ],
  reason: [
    {required: true, message: '字段不能为空', trigger: 'blur'},
    // 其他规则...
  ],
  // 其他字段的规则...
  // 更多字段...
};
// 添加数据弹窗控制
let dialogVisibleAdd = ref(false);
let addData = reactive({});
const addDataForm = ref(null);
const SubmitAddLoading = ref(false);

//设置可选择的教室null
const our_classroom = ref(null);
//加载data_config.json文件为对象
const loadConfig = async () => {
  try {
    const response = await fetch('/data_config.json'); // 假设文件在 public 目录下
    const config = await response.json();
    our_classroom.value = config.our_classroom_data;
  } catch (error) {
    console.error('加载配置失败:', error);
  }
};


//提交添加的数据
const handleSubmitAdd = async () => {
  //如果表单验证没有通过
  // 触发表单校验
  try {
    await addDataForm.value.validate();

    // 校验通过后执行提交
    SubmitAddLoading.value = true;
    // 在这里你可以处理表单提交逻辑
    //去除this.newData.author中元素为空的元素
    try {
      // 尝试使用当前的access_token获取数据
      let api_url = '';
      if (props.isAdmin) {
        api_url = '/courseadjustmentmanagement/addforadmin/';
      } else {
        api_url = '/courseadjustmentmanagement/add/';
      }
      const response = await jsonApi(api_url, JSON.stringify(addData));

      const data = await response.json();

      // 检查返回的数据是否包含错误信息，表明token可能无效或过期
      if (response.status === 201 || response.status === 200) {
        refresh();


        SubmitAddLoading.value = false;
        dialogVisibleAdd.value = false;

      } else {
        //执行父组件的方法
        // dialogVisibleAdd = false;
        ElMessage({
          type: 'error',
          message: data.error
        });
        SubmitAddLoading.value = false;

      }

      // 如果没有错误，则返回数据


    } catch (error) {
      // 网络错误或其他非token导致的错误
      SubmitAddLoading.value = false;
      throw error;
    }
  } catch (error) {
    // 表单验证失败
    // 显示错误信息
    ElMessage({
      type: 'error',
      message: '请填写完整的正确信息'
    });
    SubmitAddLoading.value = false;
  }
}
// 使用defineEmits声明事件
const emit = defineEmits(['refresh-table']);

function refresh() {
  emit('refresh-table', {});
}

// 重置表单数据
const resetFormData = () => {
  dialogVisibleAdd.value = false;
};

function showError(message, error, duration) {
  console.error(message, error);
  // 实现错误展示逻辑，例如使用通知组件
}

function getSchoolTerm(date) {
  const currentYear = date.getFullYear();
  const currentMonth = date.getMonth() + 1; // 月份是从0开始的

  // 确定学年
  let startYear, endYear;
  if (currentMonth >= 8 || currentMonth <= 1) { // 9月至次年2月属于秋季学期
    startYear = currentYear;
    endYear = currentYear + 1;
  } else { // 2月至7月属于春季学期
    startYear = currentYear - 1;
    endYear = currentYear;
  }

  // 确定学期
  let term;
  if (currentMonth >= 2 && currentMonth <= 7) {
    term = '春季学期';
  } else {
    term = '秋季学期';
  }

  return `${startYear}-${endYear}学年${term}`;
}

// 设置暴露给父组件的变量
// 暴露 count 给父组件
defineExpose({
  dialogVisibleAdd, // 暴露 count 变量
});
//当组件打开的时候执行
onMounted(() => {
  // 在这里执行组件打开时的逻辑
  // 例如，你可以调用一个函数来获取数据
  addData.term = getSchoolTerm(new Date());
  loadConfig()
});


</script>
<style scoped>

</style>